package org.amphiprion.gameengine;

import java.util.ArrayList;
import java.util.List;

import org.amphiprion.gameengine.util.Vector4;

public class Group2D implements IObject2D {
	protected List<IObject2D> objects = new ArrayList<IObject2D>();
	private IObject2D parent;
	private int x;
	private int y;
	private float globalScale = 1.0f;
	private boolean visible = true;

	public Vector4 clipping;

	public void addObject(IObject2D o) {
		objects.add(o);
		o.setParent(this);
		o.setGlobalScale(globalScale);
	}

	@Override
	public void removeObject(IObject2D o) {
		objects.remove(o);
	}

	public int count() {
		return objects.size();
	}

	@Override
	public void draw(float[] mMVPMatrix, float[] mViewMatrix, float[] mModelMatrix, float[] mProjectionMatrix, ScreenProperty sp) {
		if (clipping != null) {
			sp.pushClipping(clipping);
		}

		// for (int i = objects.size() - 1; i >= 0; i--) {
		List<IObject2D> clones = new ArrayList<IObject2D>(objects);
		for (IObject2D o : clones) {
			o.draw(mMVPMatrix, mViewMatrix, mModelMatrix, mProjectionMatrix, sp);
		}
		clones.clear();
		clones = null;

		if (clipping != null) {
			sp.popClipping();
		}
	}

	@Override
	public void setParent(IObject2D parent) {
		this.parent = parent;
	}

	@Override
	public IObject2D getParent() {
		return parent;
	}

	@Override
	public int getX() {
		return x;
	}

	@Override
	public void setX(int x) {
		int diff = x - this.x;
		for (IObject2D o : objects) {
			o.setX(o.getX() + diff);
		}
		this.x = x;
	}

	@Override
	public void setY(int y) {
		int diff = y - this.y;
		for (IObject2D o : objects) {
			o.setY(o.getY() + diff);
		}
		this.y = y;
	}

	@Override
	public int getY() {
		return y;
	}

	@Override
	public void setScale(float scale) {
		this.globalScale = scale;
		for (IObject2D o : objects) {
			o.setScale(scale);
		}
	}

	@Override
	public float getScale() {
		return globalScale;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.amphiprion.gameengine3d.IObject2D#setGlobalScale(float)
	 */
	@Override
	public void setGlobalScale(float globalScale) {
		this.globalScale = globalScale;
		for (IObject2D o : objects) {
			o.setGlobalScale(globalScale);
		}
	}

	/**
	 * @return the globalScale
	 */
	public float getGlobalScale() {
		return globalScale;
	}

	/**
	 * @return the objects
	 */
	public List<IObject2D> getObjects() {
		return objects;
	}

	@Override
	public boolean isVisible() {
		return visible;
	}

	@Override
	public void setVisible(boolean visible) {
		this.visible = visible;
	}

	public void clear() {
		objects.clear();
	}
}
